package com.photoeditor.demo.util;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.widget.Toast;

import com.common.base.ComponentContext;
import com.photoeditor.demo.app.AppApplication;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 系统接口
 */
public final class AndroidDevice {
    public static final String ACTION_CAMERA = "android.media.action.STILL_IMAGE_CAMERA";

    /**
     * 启动程序
     * @param context
     * @param action
     */
    public static final void startActivity(final Context context, String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK + Intent.FLAG_ACTIVITY_SINGLE_TOP);
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 调用通话
     * @param context
     */
    public static final void startDial(final Context context) {
        Intent intent;
        PackageManager pManager = context.getPackageManager();

        // 方式1问题：有些机型找不到拨号程序
        intent = new Intent(Intent.ACTION_DIAL);
        List<ResolveInfo> infos = pManager.queryIntentActivities(intent,
                PackageManager.GET_RESOLVED_FILTER | PackageManager.GET_INTENT_FILTERS
                        | PackageManager.MATCH_DEFAULT_ONLY);

        if (null == infos || infos.size() == 0) {
            // 方式2问题：这种方式在HD 2.3.3系统上这样起拨号，进入界面无历史纪录显示
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.parse("tel:");
            intent.setData(uri);
        }
        if (null != infos) {
            infos.clear();
            infos = null;
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//
//    /**
//     * 调用短信
//     * @param context
//     */
//    public static final void startSMS(final Context context) {
//        if (Machine.IS_SDK_ABOVE_KITKAT) {
//            try {
//                if (context != null) {
//                    String defaultSmsPackageName = Util.getDefaultSmsPackage(context);
//                    Intent intent = null;
//                    if (defaultSmsPackageName != null) {
//                        intent = Tool.getIntentByPackageName(context, defaultSmsPackageName);
//                    } else {
//                        intent = Tool.getIntentByPackageName(context, "com.google.android.talk");
//                    }
//                    if (intent != null) {
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        context.startActivity(intent);
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        } else {
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.setType("vnd.android.cursor.dir/mms");
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            try {
//                context.startActivity(intent);
//            } catch (Exception e) {
//                e.printStackTrace();
//                intent.setType("vnd.android-dir/mms-sms");
//                try {
//                    context.startActivity(intent);
//                } catch (Exception e1) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }




    /**
     * 调用浏览器
     * @param context
     */
    public static final void startBrowser(final Context context, final String url) {
        Uri uri = null;

        if (url == null) {
            uri = Uri.parse("http://www.google.com");
        } else {
            uri = Uri.parse(url);
        }

        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    /**
//     * 调用图片
//     * @param context
//     */
//    public static void startPic(final Context context) {
//        List<ResolveInfo> list = getActivities(context);
//        try {
//            if (findAndLaunchActivity(list, ".gallery", context)) {
//                return;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        try {
//            if (findAndLaunchActivity(list, ".album", context)) {
//                return;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private static final List<ResolveInfo> getActivities(final Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        return context.getPackageManager().queryIntentActivities(intent, 0);
    }
//
//    private static final boolean findAndLaunchActivity(List<ResolveInfo> list, String key,
//                                                       final Context context) {
//        if (list == null || key == null) {
//            return false;
//        }
//        String findKey = key.toLowerCase();
//        Object bject = null;
//        ResolveInfo info = null;
//        for (int i = 0, count = list.size(); i < count; i++) {
//            bject = list.get(i);
//            if (bject instanceof ResolveInfo) {
//                info = (ResolveInfo) bject;
//                if (info.activityInfo.name == null) {
//                    continue;
//                }
//                if (info.activityInfo.name.toLowerCase().indexOf(findKey) > -1) {
//                    launchActivity(info.activityInfo.packageName, info.activityInfo.name, null,
//                            context);
//                    return true;
//                }
//            }
//        }
//        return false;
//    }

    /**
     * 调用音乐
     * @param context
     */
    public static void startMusic(final Context context) {
//		Intent intent = new Intent("android.intent.action.MUSIC_PLAYER");
        //解决某些机器不能启动音乐播放器或者少一些可选的播放器的问题，
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, null);
        intent.setDataAndType(uri, "audio/mp3");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 防止状态栏下拉
     */
    public static final void collapseStatusbar(final Context context) {
        Object localObject1 = context.getSystemService("statusbar");

        if (localObject1 == null) {
            return;
        }

        Method[] arrayOfMethod = localObject1.getClass().getMethods();
        int nCount = arrayOfMethod.length;
        for (int j = 0; j < nCount; j++) {
            Method localMethod = arrayOfMethod[j];
            if (localMethod.getName().compareTo("collapse") == 0) {
                try {
                    localMethod.invoke(localObject1, (Object[]) null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    /**
     * 获取版本号
     * @param context
     * @return
     */
    public static String getVersionCode(Context context) {
        String version = "unknown";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (info != null) {
                version = "" + info.versionCode;
            }
        } catch (Exception e) {
        }
        return version;
    }

    /**
     * 获取版本名称
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String version = "unknown";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (info != null) {
                version = "" + info.versionName;
            }
        } catch (Exception e) {
        }
        return version;
    }


    /**
     * 检查是否安装某包
     * @param context
     * @param packageName 包名
     * @return
     */
    public static boolean isAppExist(final Context context, final String packageName) {
        try {
            context.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
        } catch (NameNotFoundException e) {
            return false;
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 判断程序是否安装（通过intent-filter验证）
     * @param context
     * @param intent
     * @return
     */
    public static boolean isAppExist(final Context context, final Intent intent) {
        List<ResolveInfo> infos = null;
        try {
            infos = context.getPackageManager().queryIntentActivities(intent, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (infos != null) && (infos.size() > 0);
    }

    /**
     * 检测服务是否已启动
     * @param context
     * @param className
     * @return
     */
    public static boolean isServiceRunning(final Context context, final String className) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningServiceInfo> list = am.getRunningServices(50);

        for (RunningServiceInfo info : list) {
            if (info.service.getClassName().equals(className)) {
                return true;
            }
        }

        return false;
    }


    static public boolean isChinese(Context context) {
        return context.getResources().getConfiguration().locale.equals(Locale.SIMPLIFIED_CHINESE)
                || context.getResources().getConfiguration().locale
                .equals(Locale.TRADITIONAL_CHINESE);
    }

    /**
     * 进入清除默认桌面界面
     * @param context
     * @param packageName
     */
    public static void showAppDetails(Context context, String packageName) {
        final String mSCHEME = "package";
        /**
         * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.1及之前版本)
         */
        final String appPkgName21 = "com.android.settings.ApplicationPkgName";
        /**
         * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.2)
         */
        final String appPkgName22 = "pkg";
        /**
         * InstalledAppDetails所在包名
         */
        final String aPPDefaultPackageName = "com.android.settings";
        /**
         * InstalledAppDetails类名
         */
        final String aPPDefailsClassName = "com.android.settings.InstalledAppDetails";

        Intent intent = new Intent();
        final int apiLevel = Build.VERSION.SDK_INT;
        if (apiLevel >= 9) {
            // 2.3（ApiLevel 9）以上，使用SDK提供的接口
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            Uri uri = Uri.fromParts(mSCHEME, packageName, null);
            intent.setData(uri);
        } else {
            // 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）
            // 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。
            final String appPkgName = apiLevel == 8 ? appPkgName22 : appPkgName21;
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName(aPPDefaultPackageName, aPPDefailsClassName);
            intent.putExtra(appPkgName, packageName);
        }

        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取默认桌面包名
     * @param context
     * @return
     */
    public static String getDefaultLauncherPackage(Context context) {
        PackageManager pm = context.getPackageManager();

        // 默认列表
        List<ComponentName> componentNames = new ArrayList<ComponentName>();
        List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
        pm.getPreferredActivities(intentFilters, componentNames, null);

        // Launcher
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.HOME");
        intent.addCategory("android.intent.category.DEFAULT");
        List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);

        int launcherSz = infos.size();
        int preferredSz = componentNames.size();
        for (int i = 0; i < launcherSz; i++) {
            ResolveInfo info = infos.get(i);
            if (null == info) {
                continue;
            }
            String packageStr = info.activityInfo.packageName;
            if (null == packageStr) {
                continue;
            }

            for (int j = 0; j < preferredSz; j++) {
                ComponentName componentName = componentNames.get(j);
                if (null == componentName) {
                    continue;
                }
                if (packageStr.equals(componentName.getPackageName())) {
                    return packageStr;
                }
            }
        }

        return null;
    }


    /**
     * 获取是否自动调节亮度
     * @param context
     * @return
     */
    public static boolean isAutoBrightness(Context context) {
        ContentResolver contentResolver = context.getContentResolver();

        boolean autoBrightness = false;
        try {
            autoBrightness = Settings.System.getInt(contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
        } catch (Settings.SettingNotFoundException e) {

        }
        return autoBrightness;

    }

    /**
     * 获取屏幕亮度
     * @param context
     * @return
     */
    public static int obtainBrightness(Context context) {
        int brightness = 200;
        try {
            brightness = Settings.System.getInt(context.getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
        }
        return brightness;
    }

    /**
     * SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     * @param context
     * @param mode
     */
    public static void setBrightnessMode(Context context, int mode) {
        Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, mode);
    }

    /**
     * 设置当前屏幕亮度值 0--255，并使之生效
     */
    public static void setBrightness(Context context, int bright) {
        // 保存设置的屏幕亮度值
        Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, bright);
    }

    /**
     * 保存亮度设置状态
     * @param resolver
     * @param brightness
     */
    public static void saveBrightness(ContentResolver resolver, int brightness) {
        Uri uri = Settings.System
                .getUriFor("screen_brightness");
        Settings.System.putInt(resolver, "screen_brightness",
                brightness);
        resolver.notifyChange(uri, null);
    }


    public static void startWebView(Context context, String uri) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "sorry,your mobile can't be supported", Toast.LENGTH_LONG).show();
        }
    }


    /**
     * @param title
     * @param source
     */
    public static void shareText(Context context, String title, String source) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, title);
        shareIntent.putExtra(Intent.EXTRA_TEXT, source);
        try {
            context.startActivity(Intent.createChooser(shareIntent, title));
        } catch (ActivityNotFoundException e) {
            Toast.makeText(ComponentContext.getContext(), "share fail", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param context
     * @param title     选择标题
     * @param apkFile   文件路径
     * @param safeCheck 是否检查是否存在相应的INTENT
     * @return 0：没有蓝牙程序 -1：出错 1：成功
     */
    public static int shareApkWithBT(Context context, String title, String apkFile, boolean safeCheck) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        // MIME of .apk is "application/vnd.android.package-archive".
        // but Bluetooth does not accept this. Let's use "*/*" instead.
        intent.setType("*/*");
        // Append file and send Intent
        intent.setPackage("com.android.bluetooth");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(apkFile)));
        if (safeCheck) {
            boolean isExist = isAppExist(context, intent);
            if (!isExist) {
                return 0;
            }
        }
        try {
            context.startActivity(Intent.createChooser(intent, title));
        } catch (ActivityNotFoundException e) {
            return -1;
        }
        return 1;
    }

    public static boolean isAppOnForeground(Context context) {

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断当前网络是否可以使用
     * @param context
     * @return
     */
    public static boolean isNetworkOK(Context context) {
        boolean result = false;
        if (context != null) {
            try {
                ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (cm != null) {
                    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.isConnected()) {
                        result = true;
                    }
                }
            } catch (NoSuchFieldError e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 是否连接WIFI
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        }

        return false;
    }

    public static String getNetworkTypeName() {
        try {
            ConnectivityManager cm = (ConnectivityManager) AppApplication.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                NetworkInfo networkInfo = cm.getActiveNetworkInfo();
                if (networkInfo != null) {
                    return networkInfo.getTypeName();
                }
            }
        } catch (Exception e) {

        }
        return "un_known";
    }

}
